package mall

import (
	"context"
	"fmt"
	"sync"

	"jgt-sdk/asapi"
	"jgt-sdk/utils"
)

var (
	internalHandle *Handle
	once           sync.Once
)

// InitMall 初始化运营服务
func InitMall(as *asapi.APIHandle) *Handle {
	once.Do(func() {
		internalHandle = &Handle{
			as:       as,
			identify: "MALL",
			lock:     new(sync.RWMutex),
		}
	})
	return internalHandle
}

// GetHandle 获取运营服务
func GetHandle() *Handle {
	return internalHandle
}

// Handle 运营服务
type Handle struct {
	as       *asapi.APIHandle
	identify string
	host     string
	lock     *sync.RWMutex
	traceID  string
}

func (a *Handle) getHost() string {
	a.lock.RLock()
	host := a.host
	a.lock.RUnlock()
	if host == "" {
		a.lock.Lock()
		defer a.lock.Unlock()
		v, err := a.as.GetServiceHost(a.identify)
		if err == nil && v != "" {
			host = v
			a.host = v
		}
	}
	return host
}

func (a *Handle) getContext() context.Context {
	return utils.NewTraceIDContext(context.Background(), a.traceID)
}

// GetURL 获取URL
func (a *Handle) GetURL(router string) (string, error) {
	host := a.getHost()
	if host == "" {
		return "", fmt.Errorf("无效的Host")
	}
	return utils.RequestURL(host, router), nil
}

// AddUser 增加用户
func (a *Handle) GetCollectNum(userID string) (int, error) {
	urlStr, err := a.GetURL(fmt.Sprintf("/srv/v1/user/collect/num/%s", userID))
	if err != nil {
		return 0, err
	}

	var result int
	err = utils.GetWithToken(a.getContext(), urlStr, a.as.GetTokenHandle().Get, nil, &result)
	if err != nil {
		return 0, err
	}

	return result, nil
}
